package com.zxl.template.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.luliang.shapeutils.DevShapeUtils;
import com.luliang.shapeutils.shape.DevShape;
import com.zxl.template.R;
import com.zxl.template.activity.DocDetailActivity;
import com.zxl.template.base.BaseFrag;
import com.zxl.template.base.IActivity;
import com.zxl.template.http.JsonCallback;
import com.zxl.template.model.DocRows;
import com.zxl.template.model.Search;
import com.zxl.template.model.SearchRow;
import com.zxl.template.view.pop.DocSearchPop;
import com.zxl.zlibrary.tool.LActivityTool;
import com.zxl.zlibrary.tool.LEmptyTool;
import com.zxl.zlibrary.tool.LogTool;
import com.zxl.zlibrary.view.LClearEditText;
import com.zxl.zlibrary.view.statusview.LStatusView;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;

/*
 * @created by LoveLing on 2018/11/20
 * @emil 1079112877@qq.com
 * description:查询
 */
public class QueryFrag extends BaseFrag implements IActivity {
    private static final String TAG = "QueryFrag";
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.status_view)
    LStatusView statusView;

    private Unbinder unbinder;

    @BindView(R.id.rl_title_bar)
    RelativeLayout rlTitleBar;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.et_keyword)
    LClearEditText etKeyword;

    private String docType;
    private int rows = 50;
    private int page = 1;
    private String title;
    private String gwz;
    private String qh;
    private String unit;
    private String begTime;
    private String endTime;

    private List<SearchRow> searchRowList = new ArrayList<>();
    private RvAdapter rvAdapter;


    public static BaseFrag getInstance() {
        return new QueryFrag();
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_query_n, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        return inflate;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
        initListener();
    }

    @Override
    public void initListener() {

    }


    @OnClick({R.id.iv_search, R.id.tv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_search:
                DocSearchPop pop = new DocSearchPop(getActivity(), rlTitleBar);
                pop.setOnQueryClickListener((docType, title, content, yearNumber, issueNumber, startDate, endDate) -> {
//                    收文
                    if (docType) {
                        this.docType = "1";
                    } else {
                        this.docType = "0";
                    }

                    this.gwz = content;
                    this.unit = yearNumber;
                    this.qh = issueNumber;
                    this.begTime = startDate;
                    this.endTime = endDate;

                    initNet();
                });

                pop.setOnAllListener(() -> {
                    this.gwz = null;
                    this.unit = null;
                    this.qh = null;
                    this.begTime = null;
                    this.endTime = null;
                    this.docType = null;

                    initNet();

                    pop.dismiss();
                });


                pop.toggle();
                break;
            case R.id.tv_search:
                title = Objects.requireNonNull(etKeyword.getText()).toString();
                initNet();

                break;
            default:

                break;
        }
    }

    @Override
    public void initData() {
        statusView.setOnViewRefreshListener(this::initNet);
        initNet();
    }

    private void initNet() {
        statusView.onLoadingView();
        mApi.searchJson(this, docType, page, rows, title, gwz, qh, unit, begTime, endTime, new JsonCallback<Search>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogTool.e(TAG, e);
                if (LEmptyTool.isNotEmpty(statusView))
                    statusView.onErrorView();
            }

            @Override
            public void onResponse(Search search, int i) {
                searchRowList.clear();
                searchRowList.addAll(search.searchRows);
                rvAdapter.notifyDataSetChanged();

                if (LEmptyTool.isNotEmpty(statusView))
                    statusView.onSuccessView();
            }
        });
    }

    @Override
    public void initView() {
        DevShapeUtils.shape(DevShape.RECTANGLE).solid(R.color.white).line(1, R.color.colorLine).radius(16).into(etKeyword);
        DevShapeUtils.shape(DevShape.RECTANGLE).solid(R.color.colorPrimary).line(1, R.color.colorLine).radius(16).into(tvSearch);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        rvAdapter = new RvAdapter(searchRowList);
        recyclerView.setAdapter(rvAdapter);

        rvAdapter.setOnItemClickListener((adapter, view, position) -> {
            SearchRow item = (SearchRow) adapter.getItem(position);
            DocRows docRows = new DocRows();
            assert item != null;
            docRows.documentId = item.documentId;
            docRows.documentType = item.documentType;

            Bundle args = new Bundle();
            args.putSerializable("data", docRows);
            //冲查询过去不能改稿
            args.putString("other", "");
            LActivityTool.startActivity(args, DocDetailActivity.class);
        });


    }

    class RvAdapter extends BaseQuickAdapter<SearchRow, BaseViewHolder> {

        public RvAdapter(@Nullable List<SearchRow> data) {
            super(R.layout.item_doc_collect, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, SearchRow item) {
            helper.setText(R.id.tv_title, item.title);
            helper.setText(R.id.tv_doc_type, item.documentType == 1 ? " 收文 " : "发文");
            helper.setText(R.id.tv_name, item.fromUnit);
            helper.setText(R.id.tv_time, item.createTime);

            if (item.documentType == 1) {
                helper.setBackgroundRes(R.id.tv_doc_type, R.color.colorPrimary);
            } else {
                helper.setBackgroundRes(R.id.tv_doc_type, R.color.textGreen);
            }

        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
